package com.badger.pattern;

/**
 * 单例模式
 * @author liqi
 *
 */
public class TestSingleton {
    public static void main(String[] args) {
        // 饿汉模式
        HungerSingleton hungerSingleton = HungerSingleton.getInstance();
        System.out.println(hungerSingleton);
        // 懒汉模式
        LazySingleton lazySingleton = LazySingleton.getInstance();
        System.out.println(lazySingleton);
        // 线程安全的
        Singleton uniqueInstance = Singleton.getInstance();
        System.out.println(uniqueInstance);
    }
}

/**
 * 饿汉模式
 * @author liqi
 *
 */
class HungerSingleton {
    private final static HungerSingleton HUNGER_SINGLETON = new HungerSingleton();

    private HungerSingleton() {

    }

    public static HungerSingleton getInstance() {
        return HUNGER_SINGLETON;
    }
}

/**
 * 懒汉模式
 * @author liqi
 *
 */
class LazySingleton {
    private static LazySingleton lazySingleton;

    private LazySingleton() {

    }

    public static LazySingleton getInstance() {
        if (null == lazySingleton) {
            lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }
}

/**
 * 线程安全的
 * @author liqi
 *
 */
class Singleton {
    private volatile static Singleton uniqueInstance;

    private Singleton() {

    }

    // 双重加锁校验
    public static Singleton getInstance() {
        if (null == uniqueInstance) {
            synchronized (Singleton.class) {
                if (null == uniqueInstance) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }

    // 独占锁
    public static synchronized Singleton getInstanceForSynchronized() {
        if (null == uniqueInstance) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}